﻿using CK.Sprite.Form.Core;
using CK.Sprite.Framework;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CK.Sprite.Form.Business
{
    public class StockQtyDomainService : DomainService, IBusinessExec
    {
        public SpriteObjectLocalCache _spriteObjectLocalCache => LazyGetRequiredService(ref spriteObjectLocalCache);
        private SpriteObjectLocalCache spriteObjectLocalCache;

        // 参数信息{applicationCode,tenantCode,Params}
        public async Task<JObject> ExecBusinessMethod(JObject execParams, IUnitOfWork unitOfWork = null)
        {
            var applicationCode = execParams["applicationCode"].ToString();
            var tenantCode = execParams["tenantCode"].ToString();
            var itemCode = string.Empty;
            var itemName= string.Empty;
            var itemId = string.Empty;
            var stockId = string.Empty;
            var stockCode = string.Empty;
            decimal quantity = 0;
            if(execParams["params"] != null)
            {
                if (execParams["params"]["paramValues"]["itemCode"] != null)
                {
                    itemCode = execParams["params"]["paramValues"]["itemCode"].ToString();
                }
                if (execParams["params"]["paramValues"]["itemName"] != null)
                {
                    itemName = execParams["params"]["paramValues"]["itemName"].ToString();
                }
                if (execParams["params"]["paramValues"]["itemId"] != null)
                {
                    itemId = execParams["params"]["paramValues"]["itemId"].ToString();
                }
                if (execParams["params"]["paramValues"]["stockId"] != null)
                {
                    stockId = execParams["params"]["paramValues"]["stockId"].ToString();
                }
                if (execParams["params"]["paramValues"]["stockCode"] != null)
                {
                    stockCode = execParams["params"]["paramValues"]["stockCode"].ToString();
                }
                if (execParams["params"]["paramValues"]["quantity"] != null)
                {
                    quantity = decimal.Parse(execParams["params"]["paramValues"]["quantity"].ToString());
                }
            }
              
            if (unitOfWork == null)
            {
                var businessConfig = await TenantConfigStore.FindAsync(applicationCode, tenantCode);
                await _serviceProvider.DoDapperServiceAsync(businessConfig, async (unitOfWorkNew) =>
                {
                    var stockQtyRepository = ConnectionFactory.GetConnectionProvider(BusinessConsts.BusinessConnProviderKey).GetRepository<IStockQtyRepository>(unitOfWorkNew);
                    await DoExecBusinessMethod(stockQtyRepository,itemCode,itemName,itemId,stockId,stockCode,quantity,applicationCode);
                });
            }
            else
            {
                var stockQtyRepository = ConnectionFactory.GetConnectionProvider(BusinessConsts.BusinessConnProviderKey).GetRepository<IStockQtyRepository>(unitOfWork);
                await DoExecBusinessMethod(stockQtyRepository, itemCode, itemName, itemId, stockId, stockCode, quantity, applicationCode);
            }

            return new JObject();
        }

        private async Task DoExecBusinessMethod(IStockQtyRepository stockQtyRepository, string itemCode,string itemName,string itemId,string stockId,string stockCode,decimal quantity, string applicationCode)
        {
            //判断仓库量表是否存在该物料量表，如果存在则增加，如果不存在则新增
            int checkResult = stockQtyRepository.CheckStockQtyAsync(stockCode, itemCode);
            if(checkResult >0)
            {
               await stockQtyRepository.UpdateStockQtyAsync(stockCode, itemCode, quantity);
            }
            else
            {
                var objStockQtys = _spriteObjectLocalCache.GetAll(applicationCode).FirstOrDefault(r => r.Name == "StockQty_t");
                var stockQtyFields = objStockQtys.ObjectPropertyDtos.Select(r => r.Name).ToList();
                JObject addInData = new JObject();
                addInData["Id"] = Guid.NewGuid();
                addInData["ItemCode"] = itemCode;
                addInData["ItemName"] = itemName;
                addInData["ItemId"] = itemId;
                addInData["StockId"] = stockId;
                addInData["StockCode"] = stockCode;
                addInData["Quantity"] = quantity;
                addInData["AllocQty"] = 0;
                addInData["ItemState"] = "合格";
                addInData["Batch"] = "";
                addInData["Note"] = "";
                addInData["TimeStamp"] = "2022010111";
                await stockQtyRepository.AddStockQtyAsync(stockQtyFields, addInData);
            }

        }

    }
}
